package api

import (
	"context"
	"fmt"
	"net/http"
	"strings"
	"wms/model"

	"wms/internal/svc"
	"wms/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddLogic {
	return &AddLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AddLogic) Add(req *types.ApiAddRequest) (resp *types.BaseResponse, err error) {
	resp = new(types.BaseResponse)

	//1.api是否重复
	var querys []string
	var name = strings.TrimSpace(req.Name)
	if len(name) == 0 {
		resp.Code = http.StatusBadRequest
		resp.Msg = "请填写 api 名称。"
		return resp, nil
	}

	querys = append(querys, fmt.Sprintf("name='%s'", name))

	var uri = strings.TrimSpace(req.Uri)
	if len(uri) > 0 {
		querys = append(querys, fmt.Sprintf("(uri='%s' and method = '%s')", uri, req.Method))
	}

	var query = " where " + strings.Join(querys, " or ")

	apis, err := l.svcCtx.ApiModel.FindByPage(l.ctx, query)
	if err != nil {
		fmt.Printf("[Error]查询api[%s][%s]是否重复:%s\n", uri, name, err.Error())
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	for _, one := range apis {
		if one.Uri == uri && one.Method == req.Method {
			resp.Code = http.StatusBadRequest
			resp.Msg = "请求方法、路径重复"
			return resp, nil
		}

		if one.Name == name {
			resp.Code = http.StatusBadRequest
			resp.Msg = "名称重复"
			return resp, nil
		}
	}

	if len(apis) > 0 {
		fmt.Printf("api重复：%#v\n", apis)
		resp.Code = http.StatusBadRequest
		resp.Msg = "api重复"
		return resp, nil
	}

	//2.上级api是否存在
	if req.ParentId > 0 {
		_, err = l.svcCtx.ApiModel.FindOne(l.ctx, req.ParentId)
		switch err {
		case nil:
		case model.ErrNotFound:
			resp.Code = http.StatusBadRequest
			resp.Msg = "上级api不存在"
			return resp, nil
		default:
			fmt.Printf("[Error]查询上级api[%d]:%s\n", req.ParentId, err.Error())
			resp.Code = http.StatusInternalServerError
			resp.Msg = "服务内部错误"
			return resp, nil
		}
	}

	//3.入库
	_, err = l.svcCtx.ApiModel.Insert(l.ctx, &model.Api{
		Type:     req.Type,
		SortId:   req.SortId,
		ParentId: req.ParentId,
		Uri:      uri,
		Method:   req.Method,
		Name:     name,
		Remark:   req.Remark,
	})
	if err != nil {
		fmt.Printf("[Error]添加api[%s][%s][%s]:%s\n", name, req.Method, uri, err.Error())
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
	}

	resp.Code = http.StatusOK
	resp.Msg = "成功"
	return resp, nil
}
